const router = require("koa-router")();
const AccountModel = require("../models/account.js");
const LoginModel = require("../models/login.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");



router.get("/accounts", async ctx => {
	let {
		page,
		limit,
		phone,
		username,
		status,
		role,
		room_id,
		id
	} = ctx.query;
	if (page == undefined) {
		page = 0
	}
	if (limit == undefined) {
		limit = 10
	}
	const query = {};

	// 构建查询条件
	if (phone) {
		query.phone = {
			$regex: ctx.query.phone
		};
	}
	
	// 构建查询条件
	if (username) {
		query.username = {
			$regex: ctx.query.username
		};
	}
	
	if (role != undefined && role !== '0') {
		query.role = role;
	}
	
	if (room_id != undefined && room_id !== '0') {
		query.room_id = room_id;
	}
	
	
	if (status != undefined && status !== '0') {
		query.status = status;
	}
	

	if (id != undefined && id !== '0') {
		query.id = id;
	}
	var data = await AccountModel.find(query).skip(Number(page - 1) * limit).limit(Number(limit));
	var total = await AccountModel.find(query).countDocuments();
	ctx.body = {
		code: 200,
		data: data,
		total,
		msg: "ok"
	}
})

router.post("/register", async ctx => {
	const {
		username,
		phone,
		password,
		comfirm_password,
		role,
		room_id,
		car_id,
		car_number,
		status,
		create,
		modify
	} = ctx.request.body;
	if (!ctx.request.body.phone) {
		return ResultHelper.errInfo422(ctx, "未填写手机号")
	}
	const usernameTrue = await AccountModel.findOne({
		username: ctx.request.body.username
	});
	const phoneTrue = await AccountModel.findOne({
		phone: ctx.request.body.phone
	});
	if (usernameTrue) {
		return ResultHelper.errInfo422(ctx, "账号已存在")
	}
	if (phoneTrue) {
		return ResultHelper.errInfo422(ctx, "手机号已存在")
	}
	if (!ctx.request.body.password) {
		return ResultHelper.errInfo422(ctx, "未设置密码")
	}
	if (!ctx.request.body.role) {
		return ResultHelper.errInfo422(ctx, "角色未选择")
	}
	const accountPost = new AccountModel({
		username,
		phone,
		password,
		comfirm_password,
		role,
		room_id,
		car_id,
		car_number,
		status: 1,
		create,
		modify
	});
	const res = await accountPost.save();
	ctx.body = {
		msg: '注册成功',
		code: 200
	}

})

router.post("/audit", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id,
		status
	} = ctx.request.body;
	const res = await AccountModel.updateOne({
		id: id
	}, {
		$set: {
			id,
			status
		}
	});
	ctx.body = {
		code: 200,
		msg: "ok"
	}

})


router.delete("/del/account", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id
	} = ctx.request.query;
	let res = await AccountModel.deleteOne({
		id: id
	});
	ctx.body = {
		msg: 'ok'
	}
})

module.exports = router;